#pragma once
#include <iostream>
using namespace std;
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <cstring>
#include <cerrno>
#include <string>
#include <cstdlib>
//同一个路径和int型
const char *pathname = "/home/zpl/linux/";
const int proj_id = 0x6;

// 在内核中，共享内存的大小是以4KB为基本单位的，你只能用你申请的大小，建议用n*4kB整数倍
const int defaultsize = 4096; // 单位是字节
//将key转换为16进制打印
string ToHex(key_t k)
{
    char buffer[1024];
    snprintf(buffer, sizeof(buffer), "0x%x", k);
    return buffer;
}
//得到同一个key
key_t GetShmKeyOrDie()
{
    key_t k = ftok(pathname, proj_id);
    if (k < 0)
    {
        cerr << "ftok error, errno:" << errno << ", error string:" << strerror(errno) << endl;
        exit(1);
    }
    return k;
}
//选项方式不同，创建和获取复用
int CreateShmOrDie(key_t key, int size, int flag)
{
    int shmid = shmget(key, size, flag);
    if (shmid < 0)
    {
        cerr << "shmget error, errno:" << errno << ", error string:" << strerror(errno) << endl;
        exit(2);
    }
    return shmid;
}
//创建共享内存
int CreateShm(key_t key, int size)
{
    return CreateShmOrDie(key, size, IPC_CREAT | IPC_EXCL | 0666);
}
//得到共享内存
int GetShm(key_t key, int size)
{
    return CreateShmOrDie(key, size, IPC_CREAT);
}
//进行关联
void *ShmAttach(int shmid)
{
    void *addr = shmat(shmid, nullptr, 0); // nullptr挂载到哪里，由操作系统定
    if ((long long int)addr == -1)
    {
        cerr << "shmat error" << endl;
        return nullptr;
    }
    return addr;
}
//去关联
void ShmDetach(void *addr)
{
    int n = shmdt(addr);
    if (n < 0)
    {
        cerr << "shmdt error" << endl;
    }
}
//释放共享内存
void DeleteShm(int shmid)
{
    int n = shmctl(shmid, IPC_RMID, nullptr);
    if (n < 0)
    {
        cerr << "shmctl error" << endl;
    }
    else
    {
        cout << "shmctl delete shm success,shmid:" << shmid << endl;
    }
}
//打印共享内存数据结构相关信息
void ShmDebug(int shmid)
{
    struct shmid_ds shmds;
    int n = shmctl(shmid, IPC_STAT, &shmds);
    if (n < 0)
    {
        cerr << "shmctl error" << endl;
        return;
    }
    cout << "shmds.shm_segsz:" << shmds.shm_segsz << endl;
    cout << "shmds.shm_nattch:" << shmds.shm_nattch << endl;
    cout << "shmds.shm_ctime:" << shmds.shm_ctime << endl;
    cout << "shmds.shm_perm._key:" << shmds.shm_perm.__key << endl;
}
